package user

import (
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/services/feed"
	"gitee.com/mootok/mootok/src/storage/database"
	"gitee.com/mootok/mootok/src/storage/file"
	"gitee.com/mootok/mootok/src/web/api"
	"time"
)

var LinkExpirationTime = int64((48 * time.Hour).Seconds())

var FeedService feed.Service

func (*Service) GetUserInfo(userIds []int, actorId *int, userInfos *[]api.UserInfo) error {
	var users []models.User
	var userIdMap = make(map[int]*models.User)

	if err := database.Client.Where("id in (?)", userIds).Find(&users).Error; err != nil {
		return err
	}
	for i, _ := range users {
		userIdMap[users[i].ID] = &users[i]
	}

	isFans := make([]bool, len(userIds))
	isFollower := make([]bool, len(userIds))

	for i := 0; i < len(userIds); i++ {
		user := userIdMap[userIds[i]]
		avatarUrl := file.Instance.GetLink(user.AvatarUrl, LinkExpirationTime, nil)
		(*userInfos)[i].AvatarUrl = &avatarUrl
		(*userInfos)[i].Sex = &user.Sex
		(*userInfos)[i].Nickname = &user.NickName
		(*userInfos)[i].Id = &user.ID
		(*userInfos)[i].IsFans = &isFans[i]
		(*userInfos)[i].IsFollower = &isFollower[i]
	}


	if actorId != nil {
		if err := FeedService.IsFans(userIds, *actorId,&isFans); err != nil {
			return err
		}
		if err := FeedService.IsFollower(userIds, *actorId,&isFans); err != nil {
			return err
		}
	} else {
		// 未登录用户使用默认的 false
	}

	return nil
}

func (*Service) IsExists(userId int) (bool, error) {
	result := database.Client.Where("id = ?", userId).Find(&models.User{})
	if err := result.Error; err != nil {
		return false, err
	}

	if result.RowsAffected == 0 {
		return false, nil
	}
	return true, nil
}
